package com.lkw.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义全局过滤器，实现gateway的黑名单限制访问功能
 */
@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    private final static Logger Log = LoggerFactory.getLogger(BlackListFilter.class);
    // 模拟ip黑名单
    private static List<String> blackList = new ArrayList<>();

    static {
     //   blackList.add("127.0.0.1");
     //   blackList.add("192.168.75.38");
    }

    /**
     * 重写过滤方法，定制过滤逻辑
     * @param exchange  请求和响应数据
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1.获取上下文的请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 2.获取客户端ip
        String clientIP = request.getRemoteAddress().getHostString();

        // 3.判断客户端ip是否在黑名单中
        if (blackList.contains(clientIP)) {

            Log.warn("客户端IP为{}，存在黑名单中，禁止访问", clientIP);
            String data = "Request is not denied!!!";
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer wrapData = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));

            return response.writeWith(Mono.just(wrapData));
        }

        // 请求合法，可放行，执行后续的过滤器
        return chain.filter(exchange);
    }
    /**
     * 设置过滤器的优先级，值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
